package service

import (
	"errors"
	"fmt"
	"go_my_framework/app/dao"
	"go_my_framework/app/global/request"
	"go_my_framework/app/model"
)

type ArticleService struct {
}

func (a *ArticleService) GetRow(id int, title string) model.Article {
	return dao.NewArticleDaoImpl().FindRow(id, title)
}

func (a * ArticleService) GetArticleCate() {

}

func (a *ArticleService) GetList(f request.ArticleForm) ([]map[string]interface{}, int64, error) {
	var list []map[string]interface{}
	if f.Page == 0 {
		f.Page = 1
	}
	if f.Limit == 0 {
		f.Limit = 10
	}
	// 分页
	data, count, err := dao.NewArticleDaoImpl().GetList(f.Page, f.Limit, f.Title)
	if err != nil {
		return list, 0, errors.New(err.Error())
	}
	if len(data) == 0 {
		return list, 0, errors.New("没有数据")
	}

	// 分类
	cateSvc := CategoryService{}
	cate := cateSvc.GetCateMap()
	// 管理员
	adminSvc := AdminService{}
	admin := adminSvc.GetAdminMap()
	artCateSvc := ArticleCategoryService{}
	for _, v := range data {
		tmp := map[string]interface{}{
			"id":         v.Id,
			"title":      v.Title,
			"desc":       v.Desc,
			"view_count": v.ViewCount,
			"admin_name": admin[v.AdminId].RealName,
			"created_at": v.CreatedAt.Format("2006-01-02 15:04:05"),
		}
		if v.IsOpenComment == model.IsOpenCommentYes {
			tmp["is_open_comment_desc"] = "是"
		} else {
			tmp["is_open_comment_desc"] = "否"
		}
		if v.IsTop == model.IsTopYes {
			tmp["is_top_desc"] = "是"
		} else {
			tmp["is_top_desc"] = "否"
		}
		if v.IsRecommended == model.IsRecommendedYes {
			tmp["is_recommended_desc"] = "是"
		} else {
			tmp["is_recommended_desc"] = "否"
		}
		// 所属分类
		cateDesc := ""
		artCateId := artCateSvc.GetCateByArticleId(v.Id)
		for _, vv := range artCateId {
			cateDesc += "<a class='cate'>" + cate[vv] + "</a>"
		}
		tmp["cate_desc"] = cateDesc



		list = append(list, tmp)
	}
	return list, count, nil
}

func (a *ArticleService) Add(title string, desc string, content string, coverImage string, isOpenComment int8, isTop int8, isRecommended int8, adminId int) (int, error) {
	exist := a.GetRow(0, title)
	if exist.Id != 0 {
		return 0, errors.New("已存在相同标题文章")
	}
	return dao.NewArticleDaoImpl().Create(title, desc, content, coverImage, isOpenComment, isTop, isRecommended, adminId)
}


func (a *ArticleService) Edit(id int, title string, desc string, content string, coverImage string, isOpenComment int8, isTop int8, isRecommended int8, adminId int) error {
	exist := a.GetRow(0, title)
	if exist.Id != 0 && exist.Id != id {
		return errors.New("已存在相同标题文章")
	}
	fmt.Println(isOpenComment, isRecommended, isTop)
	return dao.NewArticleDaoImpl().Update(id, title, desc, content, coverImage, isOpenComment, isTop, isRecommended, adminId)
}

func (a *ArticleService) Del(id int) error {
	// 删除文章
	err := dao.NewArticleDaoImpl().Del(id)
	if err != nil {
		return err
	}
	return dao.NewArticleCategoryDaoImpl().Del(id)

}
